#!/bin/bash

# Verify a given file with given check
# This could get extended with gpg verification for example.

# defaults
MYVERIFIER="sha256"
MYSUM=""
MYFILE=""

while test $# -gt 0; do
  case $1 in
    *-verifier)
      MYVERIFIER="$2"
      shift
    ;;
    *-checksum|*-check-sum)
      MYSUM="$2"
      shift
    ;;
    *-file)
      MYFILE="$2"
      shift
    ;;
    *-outdir)
      MYOUTDIR="$2"
      shift
    ;;
    *)
      echo "Unknown parameter $1."
      echo 'Usage: verify_file --verifier sha256/sha1/md5 --checksum e712bbcbc05a707c32eb70fa4a3b0e13b6f0cc11227ff7e4451401e5a49cc729 --file file_to_verify --outdir $OUT'
      echo "NOTE: outdir is just a dummy, this service is just for verifing and fails in error case."
      exit 1
    ;;
  esac
  shift
done

FILE="${PATH##*/}"

if [ -z "$MYSUM" ]; then
  echo "ERROR: no checksum given!"
  exit 1
fi
if [ -z "$MYFILE" ]; then
  echo "ERROR: no file is given via --file parameter!"
  exit 1
fi

case "$MYVERIFIER" in
  sha256)
    VERIFYEXE='sha256sum'
    ;;
  sha1)
    VERIFYEXE='sha1sum'
    ;;
  md5)
    VERIFYEXE='md5sum'
    ;;
  *)
    echo "ERROR: unknown \"$MYVERIFIER\" checksum verifier!"
    exit 1
    ;;
esac

filesum=`${VERIFYEXE} -- "$MYFILE" | cut -f1 -d\ `
exec test "$filesum" = "$MYSUM"

